/**
 * 
 */
package com.trgis.qtmap.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.mongodb.DBObject;
import com.trgis.qtmap.community.modle.ColumnMeta;

import freemarker.core.Environment;
import freemarker.template.SimpleSequence;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 自动组装列表显示标签
 * 
 * @author zhangqian
 *
 */
@Component("mongoresult")
public class MongoResultDirective implements TemplateDirectiveModel {

	/*
	 * <table class="table table-bordered table-hover">
    	<thead>    
	   		<tr class="active">
                <th width="50px;">编号</th>
                <th>名称</th>
                <th>表格式</th>
                <th width="120px;">操作</th>
            </tr>
		</thead>
        <tbody>
            <#list tables as table>
            <tr>
                <td class="active">${table.id}</td>
                <td>${table.tableName}</td>
                <td><#list table.columns as col>${col.name}</#list></td>
                <td><a href="${host}table/showdata/${table.id}/1">查询</a>|<a href="${host}table/getform/${table.id}">添加数据</a>|<a href="${host}deltable/${table.id}">删除</a></td>
            </tr>
            </#list>
        </tbody>
    </table>
	 *  
	 *  
	 *  
	 *  (non-Javadoc)
	 * @see freemarker.template.TemplateDirectiveModel#execute(freemarker.core.Environment, java.util.Map, freemarker.template.TemplateModel[], freemarker.template.TemplateDirectiveBody)
	 */
	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		List<ColumnMeta> cols = ((SimpleSequence)params.get("columns")).toList();
		List<DBObject> list = ((SimpleSequence) params.get("list")).toList();
		Writer out = env.getOut();
		out.write("<table class=\"table table-bordered table-hover\">");
		//===========thead=============
		out.write("<thead>");
		out.write("<tr class=\"active\">");
		for (ColumnMeta cm : cols) {
			out.write("<th>"+cm.getAlias()+"</th>");
		}
		out.write("</tr>");
		out.write("</thead>");
		//==================================
		out.write("<tbody>");
		for (DBObject db : list) {
			out.write("<tr>");
			for (ColumnMeta cm : cols) {
				out.write("<td>"+db.get(cm.getName())+"</td>");
			}
			out.write("</tr>");
		}
		out.write("</tbody>");
		//==================================
		out.write("</table>");
	}

}
